<?php

namespace app\admin\controller\home;

use app\common\controller\Backend;
use think\Db;

/**
 * 会员等级管理
 *
 * @icon fa fa-circle-o
 */
class Vip extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Level;

        $categorys = Db::table('fa_vip_serve')
            ->select();
        $this->view->assign('categorys', $categorys);
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('id', 'in', [1,2,3])
                //->order('id', $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $ids = [];
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");


            if (!isset($params['status'])){
                $this->error(__('会员权益必须选择'));
            }

            if (count($params['status']) != count($params['serve_id'])){
                $this->error(__('会员权益必须选择'));
            }

            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (isset($params['status'])){
                        foreach ($params['serve_id'] as $k=>$v){
                            $relation = Db::table('fa_vip_relation')
                                ->where(['level_id'=>$row->id,'serve_id'=>$v])
                                ->find();

                            if ($params['status'][$v] == 1){
                                $countsss = 1;
                            }elseif ($params['status'][$v] == 2){
                                $countsss = 1;
                            }elseif ($params['status'][$v] == 3){
                                $countsss = 2;
                            }elseif ($params['status'][$v] == 4){
                                $countsss = 3;
                            }else{
                                $countsss = 0;
                            }

                            Db::table('fa_deduction')
                                ->where('serve_id',$v)
                                ->update([
                                    'count' => $countsss,
                                    'update_time' => time(),
                                ]);

                            if (empty($relation)){
                                $insert = Db::table('fa_vip_relation')
                                    ->insertGetId([
                                        'level_id' => $row->id,
                                        'serve_id' => $v,
                                        'create_time' => time(),
                                        'status' => $params['status'][$v],
                                    ]);
                            }else{
                                $insert = Db::table('fa_vip_relation')
                                    ->where('id',$relation['id'])
                                    ->update([
                                        'update_time' => time(),
                                        'status' => $params['status'][$v],
                                    ]);
                            }
                        }
                        unset($params['status']);
                    }

                    unset($params['serve_id']);

                    $result = $row->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $rows = Db::table('fa_vip_relation')
            ->where('level_id',$row->id)
            ->select();

        $arrs = [];
        $arr = [];

        if (!empty($rows)){
            foreach ($rows as $k=>$v){
                $arrs[$v['serve_id']] = $v['status'];
                $arr[] = $v['serve_id'];
            }
        }

        $this->view->assign("arrs", $arrs);
        $this->view->assign("arr", $arr);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
